<template>
  <div>
    <el-dialog
      title="分配用户角色"
      width="50%"
      :visible.sync="isVisible"
      @close="closeDialog"
      @open="openDialog"
    >
      <div>
        <p>当前的用户：{{ role.username }}</p>
        <p>当前的角色：{{ role.role_name }}</p>
        <p>
          分配的新角色：<el-select
            v-model="selectedRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <!-- 按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SetUserRoleDialog',
  methods: {
    closeDialog() {
      this.selectedRoleId = ''
      this.role = ''
      this.$emit('update:show', false)
    },
    openDialog() {
      console.log('SetUserRoleDialog', this.role)
      this.getRoles()
    },
    async save() {
      console.log('selectedRoleId:', this.selectedRoleId)
      if (!this.selectedRoleId) {
        return this.$message.error('请选择角色')
      }

      const { data: res } = await this.$http.put(`users/${this.role.id}/role`, { rid: this.selectedRoleId })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.$emit('getUserList')
      this.isVisible = false
    },
    async getRoles() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.roleList = res.data
    }
  },
  data() {
    return {
      isVisible: false,
      roleList: [],
      selectedRoleId: ''
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    role: {
      type: Object
    }
  },
  watch: {
    show() {
      this.isVisible = this.show
    }
  }
}
</script>
<style lang="less" scoped></style>
